//
//  NewCityDynamicVC.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/9/12.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class NewCityDynamicVC: BaseViewController {
    
    
    
    var hasmore = "-999"
    
    var page_total = "-999"
    
    var dataModels : [NewCityDynamicModel]?
    
    var page = -999

    override func viewDidLoad() {
        super.viewDidLoad()

        plainTableView.estimatedRowHeight = 100
        
        plainTableView.separatorStyle = .none
        
        plainTableView.tableFooterView = UIView()
        
        plainTableView.backgroundColor = UIColor.viewBgGrey()
        
        
        plainTableView.contentInset = UIEdgeInsetsMake(ZMNavMaxY + ZMTitlesViewH, 0, 49, 0)
        
        
        plainTableView.register(BaseTableViewCell.self, forCellReuseIdentifier: BaseTableViewCell.identifer())
  
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: NewCityDynamicListCell.self), bundle: nil), forCellReuseIdentifier: NewCityDynamicListCell.identifer())

        plainTableView.register(UINib(nibName: StringFromClass(classType: NewCityDynamicImageCell.self), bundle: nil), forCellReuseIdentifier: NewCityDynamicImageCell.identifer())

        plainTableView.register(UINib(nibName: StringFromClass(classType: NewCityDynTwoImageCell.self), bundle: nil), forCellReuseIdentifier: NewCityDynTwoImageCell.identifer())

        
        
        weak var weakSelf = self
        
        plainTableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf!.loadData()
            
        }
        
        plainTableView.mj_header.beginRefreshing()
        
        plainTableView.mj_footer = ZMRefreshFooter.init{
            
            weakSelf!.loadMoreData()
            
        }
        

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

  
}



extension NewCityDynamicVC{
    
    func loadData() {
        
        page = 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=article&a=article_list&ac_id=1", parameters: parmeter) {[weak self] (responseObject, error) in
            
            
            if error == nil {
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                self?.hasmore = "0"
                
                self?.page_total = responseObject!["page_total"] as! String
                
                self?.dataModels = [NewCityDynamicModel]()
                
                
                for dic in self!.myData() as [[String : AnyObject]]{
                    
                    self!.dataModels!.append(NewCityDynamicModel(dic: dic))
                    
                }
                
                
                if self!.dataModels!.count == 0{
                    
                    self?.showLogoView(text : "暂新城动态...")
                    
                    self!.plainTableView.mj_header.endRefreshing()
                    
                }else{
                    
                    self!.cachePictures()
                    
                }
                
                
                
                
                
            }else{
                
                self!.plainTableView.mj_header.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
        }
        
        
    }
    
    
    
    
    
    
    
    
    func loadMoreData() {
        
        page += 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=article&a=article_list&ac_id=1", parameters: parmeter) {[weak self] (responseObject, error) in
            
            
            if error == nil {
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                self?.page_total = responseObject!["page_total"] as! String
                
                var tempArray = [NewCityDynamicModel]()
                
                for dic in self!.myData() as [[String : AnyObject]]{
                    
                    let tempModel = NewCityDynamicModel(dic: dic)
                    
                    tempArray.append(tempModel)
                    
                    self!.dataModels!.append(tempModel)
                    
                }
                
                
                self!.cacheMorePictures(model: tempArray)
                
                
                
                
                
            }else{
                
                self!.plainTableView.mj_footer.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
        }
        
    }
    
    
    
    
    func cachePictures(){
        
        
        let grop = DispatchGroup()
        
        for temp in dataModels! {
            
            
            guard let url = URL(string: temp.message_cover) else {
                continue
                
            }
            
            grop.enter()
            
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                
                //                QL1("下载一张完成")
                
                grop.leave()
                
            })
            
        }
        
        grop.notify(queue: DispatchQueue.main) {
            
            
            //            QL1("全部下载完成，刷新UI")
            
            self.plainTableView.mj_footer.resetNoMoreData()
            
            
            if self.hasmore == "0" {
                
                self.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                
            }
            
            self.plainTableView.mj_header.endRefreshing()
            
            self.plainTableView.reloadData()
        }
        
    }
    
    
    func cacheMorePictures(model : [NewCityDynamicModel]){
        
        
        let grop = DispatchGroup()
        
        for temp in model {
            
            guard let url = URL(string: temp.message_cover) else {
                continue
            }
            
            grop.enter()
            
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                grop.leave()
                
            })
            
        }
        
        
        grop.notify(queue: DispatchQueue.main) {
            
            if self.hasmore == "0" {
                
                self.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                
                
            }else{
                
                self.plainTableView.mj_footer.endRefreshing()
                
            }
            
            
            
            self.plainTableView.reloadData()
            
        }
        
        
    }
    
    
    
    
    
}






extension NewCityDynamicVC{
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if dataModels == nil {
            return 0
        }
        
        if dataModels!.count > 0 {
            return 1
            
        } else {
            
            return 0
            
        }
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataModels?.count ?? 0
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let mode = dataModels?[indexPath.row]
        
        if mode?.message_type == "1" {
            
            let tableCell : NewCityDynamicListCell =  tableView.dequeueReusableCell(withIdentifier: NewCityDynamicListCell.identifer()) as! NewCityDynamicListCell
            
            tableCell.model = dataModels?[indexPath.row]
            
            return tableCell

        }else if mode?.message_type == "2" {
            let tableCell : NewCityDynTwoImageCell =  tableView.dequeueReusableCell(withIdentifier: NewCityDynTwoImageCell.identifer()) as! NewCityDynTwoImageCell
            
            tableCell.model = dataModels?[indexPath.row]

            
            return tableCell
            
        }else if mode?.message_type == "3" {
            let tableCell : BaseTableViewCell =  tableView.dequeueReusableCell(withIdentifier: BaseTableViewCell.identifer()) as! BaseTableViewCell
            
            return tableCell
        }else if mode?.message_type == "4" {
            
            let tableCell : NewCityDynamicImageCell =  tableView.dequeueReusableCell(withIdentifier: NewCityDynamicImageCell.identifer()) as! NewCityDynamicImageCell
            
            tableCell.model = dataModels?[indexPath.row]
            


            return tableCell
        }else{
        
            let tableCell : BaseTableViewCell =  tableView.dequeueReusableCell(withIdentifier: BaseTableViewCell.identifer()) as! BaseTableViewCell
            
            return tableCell

        }
        
        
           
        
    }
    
    
    
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //        super.tableView(tableView, didSelectRowAt: indexPath)
        
        let model = dataModels?[indexPath.row]
        
        if model?.message_type == "4" {
            return
        }
        
        if model != nil {
            
            let temp = UpLoadIconController()
            
            temp.urlStr = model!.message_url
            
            temp.hiddenBar = false
            
            
            navigationController?.pushViewController(temp, animated: true)
            
        }
        
        
        
    }
    
    
    
    
    
}



extension NewCityDynamicVC{


    func myData() -> [[String : Any]]{
        return [                 
            ["message_cover" : "https://mmbiz.qpic.cn/mmbiz_jpg/l57Tibg0s84B0NmEAeEm9icvSKPd8ssha9KelibhUVpwTVKrEibXkT8jTGtStetbW8FWMtJe6x9qa70h1tXcprO4VQ/640?wxfrom=5&wx_lazy=1",
                 "message_time" : "2017-07-17 18:07:00",
                 "message_title" : "新区！新区！还是新区！长江新城选址确定，新区小伙伴们嗨起来！",
                 "message_url" : "http://mp.weixin.qq.com/s/_dXlwC_3bEEo-p6jCs834Q",
                 "message_id" : "1",
                 "message_view" : "34",
                 "message_desc" : "襄阳的长江新城,我们的东津新区",
                 "message_type" : "1",
                 "subMessage_list" : []
            ],
            ["message_cover" : "https://mmbiz.qpic.cn/mmbiz_jpg/ROoDd1muZNmc7GGgOI1k6CGobdb5p9iczmwhlfS6yUCnk5wictCWmib2tNO4Tc5YMNyNqMIo5LaVziatSlv7o6tgdQ/0.jpeg?wxfrom=5&wx_lazy=1",
                  "message_time" : "2017-07-13 18:07:00",
                  "message_title" : "戳心！襄阳大街小巷惊现暖心广告，这波情怀狗粮我吃了！",
                  "message_url" : "http://mp.weixin.qq.com/s/f1RjIf8Xk0fRxtaFapDAQw",
                  "message_id" : "1",
                  "message_view" : "69",
                  "message_desc" : "一碗碗暖心鸡汤,外加一把把温馨狗粮,这次东津世纪城|环境台的广告你可吃饱,喝饱?",
                  "message_type" : "1",
                  "subMessage_list" : []
            ],
            ["message_url" : "888999",
             "message_time" : "2017-07-11 11:56:00",
             "message_type" : "4",
             "message_cover" : "https://mmbiz.qpic.cn/mmbiz_jpg/1YYHSkniajiaGIkUGzNE2yYftHZpK3dTqEIjmKp18Fic5PeTpAAgqLuvr75350oeZV9WrLhV8uLRBMBtzEYUnzszQ/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1",
             ],
            ["message_cover" : "https://mmbiz.qpic.cn/mmbiz_png/1YYHSkniajiaETOlKDWFsic57s2LevXr06WfQkoIU3m6iavYWfqibqkMux1Mk2Vs7YJtyt5qaWbBPQ0L23st88nN8mw/640?wx_fmt=png&wxfrom=5&wx_lazy=1",
                  "message_time" : "2017-07-12 18:07:00",
                  "message_title" : "揭秘|襄阳首个乘扶梯回家的楼盘",
                  "message_url" : "http://mp.weixin.qq.com/s/ykDVaDyCAxy70-1LTXcvEg",
                  "message_id" : "1",
                  "message_view" : "77",
                  "message_desc" : "襄阳东进,宏伟蓝图正一步步完成!",
                  "message_type" : "2",
                  "subMessage_list" : [[
                    
                    "subMessage_cover" : "https://mmbiz.qpic.cn/mmbiz_png/1YYHSkniajiaETOlKDWFsic57s2LevXr06Wia8O1ibFjsDgs3ibLA6fv9icpsle1PvXZsod4wr49EwYEWU1vB6N7ibibXwg/640?wx_fmt=png&wxfrom=5&wx_lazy=1",
                    "subMessage_url" : "http://mp.weixin.qq.com/s/bVQEL2PDkCg2n1KG6C7Y-A",
                    "subMessage_title" : "特大福利|东津世纪城业主优享四中、实小入学政策！家有小孩的速看！！",
                    
                    ]]
            ],
            ["message_cover" : "https://mmbiz.qpic.cn/mmbiz_jpg/1YYHSkniajiaGIkUGzNE2yYftHZpK3dTqEIjmKp18Fic5PeTpAAgqLuvr75350oeZV9WrLhV8uLRBMBtzEYUnzszQ/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1",
                 "message_time" : "2017-07-12 18:07:00",
                 "message_title" : "福利来袭|动动大拇指，就能赢小米！这样的便宜，不捡白不捡！",
                 "message_url" : "http://mp.weixin.qq.com/s/OApwt4bOz2MM7PGd-wE1Hw",
                 "message_id" : "1",
                 "message_view" : "77",
                 "message_desc" : "襄阳东进,宏伟蓝图正一步步完成!",
                 "message_type" : "2",
                 "subMessage_list" : [[
                    
                    "subMessage_cover" : "https://mmbiz.qpic.cn/mmbiz_png/1YYHSkniajiaGPHP5YPQNJkKP1jRX5yrU9xbx1jFibgxxJPn2rLiarhacIDBvqyY9wSQIKbQMjicuwp7iaIl7hN13LlA/640?wx_fmt=png&wxfrom=5&wx_lazy=1",
                    "subMessage_url" : "http://mp.weixin.qq.com/s/tfoZksvVgMWHvo4JoAOQuA",
                    "subMessage_title" : "幕后心语|暖心神文案是这样炼成的！",
                    
                    ]]
            ],
            ["message_cover" : "https://mmbiz.qpic.cn/mmbiz_jpg/1YYHSkniajiaGIkUGzNE2yYftHZpK3dTqEIjmKp18Fic5PeTpAAgqLuvr75350oeZV9WrLhV8uLRBMBtzEYUnzszQ/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1",
             "message_time" : "2017-07-11 18:07:00",
             "message_title" : "居然可以乘扶梯回家！襄阳这个楼盘逆天了啊！",
             "message_url" : "http://mp.weixin.qq.com/s/EjX0GxvskrllNmk4qzMCvA",
             "message_id" : "1",
             "message_view" : "99",
             "message_desc" : "东津世纪城|天境台,首创扶梯回家,登台入市",
             "message_type" : "1",
             "subMessage_list" : []
            ],
            ["message_cover" : "https://mmbiz.qpic.cn/mmbiz_jpg/1YYHSkniajiaHpacmE5mtVFxia9ib4s3RicKAI1jmyZJmQNa7DfxSswv2Aic3Mia48g6iczQHxUbSOicNQuKfKicYsnm7AWA/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1",
             "message_time" : "2017-07-10 18:07:00",
             "message_title" : "最新|郑万高铁好消息传出！4小时到北京，freestyle~~",
             "message_url" : "http://mp.weixin.qq.com/s/MHFc_UTdxq33vNUN-37PXA",
             "message_id" : "1",
             "message_view" : "100",
             "message_desc" : "今天上午,国家重点工程————郑万高铁湖北段在襄阳白河特大桥架起了首片箱梁!标志着郑万高铁湖北段架梁施工全面展开",
             "message_type" : "1",
             "subMessage_list" : []
            ],
            ["message_cover" : "https://mmbiz.qpic.cn/mmbiz_png/gwq5h0NxcGG9k7jVqv7sRyEHEnWGRfjxqozdAGicQk8f0j9ic1w7Hf0UlHZIBQrqYxDSwqDiakl8AU9GwibwnXTTEw/640?wxfrom=5&wx_lazy=1",
             "message_time" : "2017-06-12 18:07:00",
             "message_title" : "乐成书记发话了：“三年内打通东西轴线！”襄阳娃，燥起来！",
             "message_url" : "http://mp.weixin.qq.com/s/DOx9JDIUlskLK39jKtCpJA",
             "message_id" : "1",
             "message_view" : "13",
             "message_desc" : "李乐成调研重点城建项目时要求,让城市环线'快'起来!",
             "message_type" : "1",
             "subMessage_list" : []
            ],
            ["message_cover" : "https://mmbiz.qpic.cn/mmbiz_jpg/1YYHSkniajiaFHEDfv2icL0g0ia8h0aTvmFvhpo4FRLgdVFakHlEiaGichDMYpEMKRwtiaaJvcKTgUeiatuvoEGsoCq9EA/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1",
             "message_time" : "2017-06-29 18:07:00",
             "message_title" : "奔走相告！东津大桥与鱼梁洲年内互通！东津、鱼梁洲、襄城即将“亲密接触“",
             "message_url" : "http://mp.weixin.qq.com/s/EwxmwVLidN2KtJC0h1UZdQ",
             "message_id" : "1",
             "message_view" : "29",
             "message_desc" : "东津大桥与鱼梁洲连线工程全面复工,年内便可实现通行!",
             "message_type" : "1",
             "subMessage_list" : []
            ],
            ["message_cover" : "https://mmbiz.qpic.cn/mmbiz_jpg/1YYHSkniajiaFcgrX2S7IWySTELFedbp7xlwVFEibf7DrGzf836m15Fy5NSsB8kms2pdR260HhS0s4LBLia2gydHaw/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1",
             "message_time" : "2017-6-27 18:07:00",
             "message_title" : "东津新区最新美图来袭，你关注的学校、医院、市民中心都在这，拿走不谢！",
             "message_url" : "http://mp.weixin.qq.com/s/Gx4ZTSNrNsbQNYs4AzYLJg",
             "message_id" : "1",
             "message_view" : "15",
             "message_desc" : "12张超美图片带你看新东津!",
             "message_type" : "1",
             "subMessage_list" : []
            ],
            ["message_cover" : "http://mmbiz.qpic.cn/mmbiz_png/1YYHSkniajiaH1d0WxzpbwGfkPpu7x5dDw6H8K3rwFibZfy6qdibfPXfp9ibW6TDgSeSJQUgYMeqhiaw1krYchDLKZPQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1",
             "message_time" : "2016-11-25 18:52:00",
             "message_title" : "襄阳初雪: 你在老城区里寸步难行,我在浩然河畔美出诗意!",
             "message_url" : "http://mp.weixin.qq.com/s/nn3hwmmLftYfvGoW1ibMFA",
             "message_id" : "1",
             "message_view" : "10",
             "message_desc" : "换种画风,赏雪可好?",
             "message_type" : "1",
             "subMessage_list" : []
            ],
            ["message_cover" : "http://mmbiz.qpic.cn/mmbiz_jpg/1YYHSkniajiaHyVwvISLNGu2Tw1fpp93x0uYWesmFG3BUYK34FHziabSj7lcLYKkuN8Axs7CSMLYesUhJFl4Sk5wA/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1",
             "message_time" : "2016-11-20 19:27:00",
             "message_title" : "选择,往往比努力更重要!",
             "message_url" : "http://mp.weixin.qq.com/s/7mHojZQjy8X9YmAcPFza7g",
             "message_id" : "1",
             "message_view" : "10",
             "message_desc" : "或许你还在犹豫,那就进来看看",
             "message_type" : "1",
             "subMessage_list" : []
            ],
            ["message_cover" : "http://mmbiz.qpic.cn/mmbiz_jpg/1YYHSkniajiaHyVwvISLNGu2Tw1fpp93x04aHGk2U8iasj7vZ3F9GibXARicELDchaoynO9hfjYPhPDk2cgDLUQLEyA/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1",
                 "message_time" : "2016-11-18 18:07:00",
                 "message_title" : "市科技馆主体即将完工,'探索之眼'造型抢先看!!!",
                 "message_url" : "http://mp.weixin.qq.com/s/Q4fStCYW8jjjrs0oK8GmAQ",
                 "message_id" : "1",
                 "message_view" : "10",
                 "message_type" : "1",
                 "message_desc" : "襄阳东进,宏伟蓝图正一步步完成!",
                 "subMessage_list" : []
            ],
     
                    
                
                
        ]
    }





}

